/*
 * @Author: Zyunchao 18651805393@163.com
 * @Date: 2022-03-10 11:36:47
 * @LastEditors: Zyunchao 18651805393@163.com
 * @LastEditTime: 2022-11-29 10:42:49
 * @FilePath: /_apollo/src/microApp/lifecycle.ts
 * @Description: 微应用的生命周期核心入口文件，内部监听 micro-app 的生命周期、接收基座数据等
 */
import type { App } from 'vue'
import parentDataMsgHandle from '../parentDataMsgHandle'
import packInfo from '@ROOT/package.json'

function getColor() {
    const r = Math.floor(Math.random() * 256)
    const g = Math.floor(Math.random() * 256)
    const b = Math.floor(Math.random() * 256)
    return 'rgb(' + r + ',' + g + ',' + b + ')'
}

const color = getColor()

export default (app: App) => {
    // 监听卸载操作
    window.addEventListener('unmount', function () {
        app.unmount()
        window.microApp.removeDataListener(parentDataMsgHandle)
    })

    // 监听数据
    window.microApp.addDataListener(parentDataMsgHandle, true)

    // 子应用 keep-alive 事件
    window.addEventListener('appstate-change', function (e: any) {
        if (e.detail.appState === 'afterhidden') {
            console.log(`%c ${packInfo.name} 已卸载`, `color: ${color};`)
        } else if (e.detail.appState === 'beforeshow') {
            console.log(`%c ${packInfo.name} 即将重新渲染`, `color: ${color};`)
        } else if (e.detail.appState === 'aftershow') {
            console.log(`%c ${packInfo.name} 已经重新渲染`, `color: ${color};`)
        }
    })
}
